﻿/*
* Notification.js
* Referenced by _Layout, Master and more
*/

//DESIGN PATTERN: dunno, but it uses 'Constructor'
//NAMESPACE PATTERN: Object Literal Notation

var Config =
{
    //ContextPath: 'http://192.168.1.65:9006',
    //ContextPath: 'http://qadialer.leads360.com:8081',
    ContextPath: _contextPath,
	MVCBetaPagesEnabled: ''
};

// global
var _notification;
var _pollWait = 500;
var _stopCheckInterval = 30; // polling stop check interval (minutes)
var _notificationFireCount = 0;

// constructors
Notification = function (dbName, agentId, stopCheckInterval, audioUrl)
{
	this.DbName = dbName;
	this.AgentId = agentId;
	this.SetStopCheckTime(stopCheckInterval);
	this.AudioUrl = String(audioUrl);
};

var NotificationStatic =
{
	IsActive: false,
	Types:
	{
	    None: 0, NewLead: 1, EmailOpen: 2, InboundCall: 9, InboundCallLoser: 19
	}
};

// prototype (class)
Notification.prototype =
{
    // properties
    DbName: null,
    AgentId: null,
    Interval: null,
    LeadId: null,
    Type: null,
    StopCheckAfter: null,
    CurrentRequest: null,
    ServiceDomain: null,
    AudioUrl: null,

    // methods
    Load: function (leadId, typeId) {
        this.LeadId = leadId;
        this.Type = typeId;
    },
    SetStopCheckTime: function (stopCheckInterval) {
        // interval in minutes
        this.StopCheckAfter = new Date();
        this.StopCheckAfter.setMinutes(this.StopCheckAfter.getMinutes() + stopCheckInterval);
    },
    WaitThenPoll: function (waitTime) {
        window.setTimeout(function () { _notification.Poll(); }, waitTime);
    },
    Abort: function () {
        if (this.CurrentRequest)
            this.CurrentRequest.abort();
    },
    Poll: function () {
        if ((new Date()) < this.StopCheckAfter) {
            var url = [this.ServiceDomain, '/AsyncSubscriber.ashx'].join('');
            var dataString = ['DbName=', this.DbName, '&AgentId=', this.AgentId, '&TypeId=1'].join('');

            this.CurrentRequest = $.jsonp(
			{
			    url: url,
			    data: dataString,
			    callbackParameter: 'callback',
			    success: function (simpleNotification) {
			        // Console
			        if (simpleNotification) {
			            if (simpleNotification.TypeId > 0) {
			                switch (simpleNotification.TypeId) {

			                    //#region Inbound Call                                                        
			                    case NotificationStatic.Types.InboundCall:
			                        // Apply show a popup here
                                    $.ajax({
                                        type: "POST",
                                        url: "/Lead/GetLeadNameBy",
                                        data: {leadID: simpleNotification.ItemId},
                                        dataType: "json",
                                        success: function (model, textStatus, jqXHR) {
                                            if (model != undefined) {
                                                $('#leadCallId').text(model);
                                                $('#viewLeadCallLink').attr("href", "/Lead/Edit/" + simpleNotification.ItemId);
                                                $('#leadCallNotification').showAlert({
                                                    width: 380
                                                });
                                            }
                                            else {
                                                closePopupError();
                                            }
                                        },
                                        error: function (xhr, status, error) {
                                            closePopupError();
                                        }
                                    });

                                    _notification.Poll();
				                    
			                        break;
			                    case NotificationStatic.Types.InboundCallLoser:
			                        // Apply hide a popup here
			                        // $('#leadCallNotification').hide();
			                        // And after that will call a poll again
			                        _notification.Poll();
			                        break;
			                    //#endregion Inbound Call                                                          

			                    default:
			                        _notification.WaitThenPoll(_pollWait);
			                        break;
			                }
			            }
			            else {
			                _notification.WaitThenPoll(_pollWait);
			            }
			        }
			    },
			    error: function (d, msg) {
			        // Maybe we should log or something??
			    }
			});
        }
    }
};

//-------------------------------------------------------------------------------------
function NotificationInit(db, agentId, audioUrl, stopCheckInterval)
{
	if (stopCheckInterval == 0)
		stopCheckInterval = _stopCheckInterval;
	_notification = new Notification(db, agentId, stopCheckInterval, audioUrl);
	//console.log("Notification");
}

function NotificationInitBeginPoll(serviceDomain)
{
	_notification.ServiceDomain = serviceDomain;
	_notification.WaitThenPoll(_pollWait);
	//console.log("Begin Poll");
}

$(function ()
{
	$(window).unload(function ()
	{
		if (_notification)
			_notification.Abort();
	});
});

// Config information
var db = _dbName;
var agentId = _agentId;
var audioUrl = "";
var stopCheckInterval = 30;

// Init
NotificationInit(db, agentId, audioUrl, stopCheckInterval);
NotificationInitBeginPoll(Config.ContextPath);